<?php
// $Id$
/**
 * @file
 * Display a list of requests for a hospital radio station.
 *
 * This file contains the real implementations.
 *
 * Copyright 2009 Frank Heinley.
 *
 * This file is part of fhreqchart.
 *
 * fhreqchart is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * fhreqchart is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with fhreqchart.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Real implementation of hook_menu().
 */
function _fhreqchart_menu() {
  $items['admin/settings/fhreqchart'] = array(
    'title' => 'Request Charts',
    'description' => 'Settings for the request charts module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('fhreqchart_settings_form'),
    'access arguments' => array('access administration pages'),
    'file' => 'fhreqchart.module.inc',
    'type' => MENU_NORMAL_ITEM,
    );

  $items['fhreqchart'] = array(
    'title' => 'Request Charts',
    'description' => 'Charts of listener requests',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('fhreqchart_chart_list'),
    'access arguments' => array('view fhreqchart'),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'fhreqchart.module.inc',
    'menu_name' => 'primary-links',
    );

  $items['fhreqchart/chart'] = array(
    'title' => 'Request Chart',
    'description' => 'Charts of listener requests',
    'access arguments' => array('view fhreqchart'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => 1,
    );

  $items['fhreqchart/report'] = array(
    'title' => 'Report',
    'description' => 'Produce a printable report',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('fhreqchart_download_form'),
    'access arguments' => array('download fhreqchart'),
    'file' => 'fhreqchart.module.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => 2,
    );

  $items['fhreqchart/record'] = array(
    'title' => 'Record a request',
    'description' => 'Record a request onto the system.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('fhreqchart_form_edit_request'),
    'access arguments' => array('record fhreqchart'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'fhreqchart.module.inc',
    'weight' => 4,
    );

  $items['fhreqchart/manage'] = array(
    'title' => 'Manage requests',
    'description' => 'Manage the list of requests.',
    'page callback' => 'fhreqchart_manage_requests',
    'access arguments' => array('manage fhreqchart'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 5,
    'file' => 'fhreqchart.manage.inc',
    );

  $items['fhreqchart/edit/%'] = array(
    'title' => 'Edit request',
    'description' => 'Edit a request',
    'page callback' => 'fhreqchart_edit_request',
    'page arguments' => array(2),
    'access arguments' => array('manage fhreqchart'),
    'file' => 'fhreqchart.module.inc',
    'type' => MENU_CALLBACK,
    );

  $items['fhreqchart/artistac'] = array(
    'title' => 'Artist autocomplete',
    'page callback' => 'fhreqchart_artist_autocomplete',
    'access arguments' => array('manage fhreqchart'),
    'file' => 'fhreqchart.module.inc',
    'type' => MENU_CALLBACK,
  );

  $items['fhreqchart/titleac'] = array(
    'title' => 'Title autocomplete',
    'page callback' => 'fhreqchart_title_autocomplete',
    'access arguments' => array('manage fhreqchart'),
    'file' => 'fhreqchart.module.inc',
    'type' => MENU_CALLBACK,
  );

  $items['fhreqchart/genreac'] = array(
    'title' => 'Genre autocomplete',
    'page callback' => 'fhreqchart_genre_autocomplete',
    'access arguments' => array('manage fhreqchart'),
    'file' => 'fhreqchart.module.inc',
    'type' => MENU_CALLBACK,
  );

  $items['fhreqchart/wardac'] = array(
    'title' => 'Ward autocomplete',
    'page callback' => 'fhreqchart_ward_autocomplete',
    'access arguments' => array('manage fhreqchart'),
    'file' => 'fhreqchart.module.inc',
    'type' => MENU_CALLBACK,
  );

  return $items;
} // _fhreqchart_menu()

/**
 * Real implementation of hook_theme()
 */
function _fhreqchart_theme() {
  return array(
    'fhreqchart_show_range' => array(
      'arguments' => array('range' => NULL),
      'file' => 'fhreqchart.themes.inc',
    ),
    'fhreqchart_total' => array(
      'arguments' => array('count' => NULL),
      'file' => 'fhreqchart.themes.inc',
    ),
    'fhreqchart_form_range' => array(
      'arguments' => array('form' => NULL),
      'file' => 'fhreqchart.themes.inc',
    ),
    'fhreqchart_report_header' => array(
      'arguments' => array('title' => NULL, 'range' => NULL),
      'file' => 'fhreqchart.themes.inc',
    ),
    'fhreqchart_manage_filter' => array(
      'arguments' => array('filter' => NULL),
      'file' => 'fhreqchart.manage.inc',
    ),
    'fhreqchart_form_manage_requests_list' => array(
      'arguments' => array('listres' => NULL),
      'file' => 'fhreqchart.manage.inc',
    ),
    'fhreqchart_edit_form' => array(
      'arguments' => array('form' => NULL),
    ),
    'fhreqchart_edit_msg' => array(
      'arguments' => array('form' => NULL),
    ),
  );
} // _fhreqchart_theme()

/**
 * FAPI definition to display the chart list.
 *
 * @ingroup forms
 */
function fhreqchart_chart_list(&$form_state) {
  fhreqchart_add_css();
  
  /* Get the range and type of search */
  if (isset($_SESSION['fhreqchart'])) {
    $range = unserialize($_SESSION['fhreqchart']);
    unset($_SESSION['fhreqchart']);
  }
  else {
    // New search
    $d = getdate();
    $month = $d['mon'] - 1;   // last months chart
    $year = $d['year'];
    if ($month < 1) {
      $month = 12;
      $year--;
    }
    $range = array(
      'month' => $month,
      'year' => $year,
      'm2' => 0,
      'y2' => 0,
    );
    $range['type'] = 'artist';
  }

  $months = fhreqchart_month_list();
  $years = fhreqchart_year_list(FALSE);
  
  $form['req_range']['caption'] = array(
    '#value' => t('Select type and period for new report.'),
  );
  $form['req_range'] += _fhreqchart_range_form($range);

  /* Display the results of the search */
  $total = fhreqchart_count_range($range);
  $form['markup'] = array(
    '#value' => theme('fhreqchart_total', $total),
  );

  $header = _fhreqchart_header_row($range);
  $rows = _fhreqchart_report_rows($range);
  $form['chart'] = array(
    '#value' => theme('table', $header, $rows),
  );
  return $form;
}

function fhreqchart_chart_list_submit(&$form, &$form_state) {
  $range['month'] = $form_state['values']['month'];
  $range['year'] = $form_state['values']['year'];
  if ($form_state['values']['month2'] == 0 or $form_state['values']['year2'] == 0) {
    $range['m2'] = 0;
    $range['y2'] = 0;
  }
  else {
    $range['m2'] = $form_state['values']['month2'];
    $range['y2'] = $form_state['values']['year2'];
  }
  $range['type'] = $form_state['values']['type'];
  $_SESSION['fhreqchart'] = serialize($range);
}

/**
 * FAPI definition of the range selection sub form.
 *
 * @param $range
 *  Array of current search values
 * @return
 *  FAPI array of the form.
 * @ingroup forms
 */
function _fhreqchart_range_form($range) {
  $months = fhreqchart_month_list();
  $years = fhreqchart_year_list(FALSE);
  
  $form['#theme'] = 'fhreqchart_form_range';

  $types['artist'] = t('Artist');
  $types['track'] = t('Track');
  if (user_access('view fhreqchart genre')) {
    $types['genre'] = t('Genre');
  }

  $form['type'] = array(
    '#type' => 'select',
    '#options' => $types,
    '#default_value' => $range['type'],
  );

  $form['month'] = array(
    '#type' => 'select',
    '#options' => $months,
    '#default_value' => $range['month'],
  );

  $form['year'] = array(
    '#type' => 'select',
    '#options' => $years,
    '#default_value' => $range['year'],
  );

  $months[0] = t('ignore');
  $years[0] = t('ignore');

  $form['month2'] = array(
    '#type' => 'select',
    '#options' => $months,
    '#default_value' => $range['m2'],
  );

  $form['year2'] = array(
    '#type' => 'select',
    '#options' => $years,
    '#default_value' => $range['y2'],
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

/**
 * Get the header row for the results table
 *
 * @param $range
 *  Array of values for the range of the search
 * @return
 *  Array of header values.
 */
function _fhreqchart_header_row($range) {
  switch ($range['type']) {
    case 'artist':
    case 'track':
      $header = array(t('Posn.'), t('Artist'), t('Titles'), t('Num.'));
      break;
    case 'genre':
      $header = array(t('Posn.'), t('Genre'), t('Num.'));
      break;
  }
  return $header;
}

/**
 * Generate the rows for the report
 *
 * @param $range
 *  Assoc array of parameters for the search
 * @return
 *  Array of values, suitable for a table
 */
function _fhreqchart_report_rows($range) {
  $res = fhreqchart_query($range);
  $rows = array();
  $tcount = 0;
  $tposn = 1;
  $realposn = 0;
  $countunspec = 0;
  $rowunspec = FALSE;
  while ($obj = db_fetch_object($res)) {
    switch ($range['type']) {
      case 'artist':
      case 'track':
        if ($obj->artistid == 1 or $obj->titleid == 1) {
          // Catch the unspecified ones, may be more than 1
          if (!$rowunspec) {
            $rowunspec[] = '-'; // posn
            $rowunspec[] = t('Unspecified');
            $rowunspec[] = t('Unspecified');
            $countunspec = $obj->counter;
          }
          else {
            $countunspec += $obj->counter;
          }
          continue 2;
        }
        break;
      case 'genre':
        if ($obj->genreid == 1) {
          // Catch the unspecified genre & move to end of list
          $rowunspec[] = '-';  // position
          $rowunspec[] = t('Unspecified');
          $countunspec += $obj->counter;
          continue 2;
        }
        break;
    } // /switch
    $realposn++;
    if ($tcount != $obj->counter) {
      $tcount = $obj->counter;
      $tposn = $realposn;
    }
    $row = array();
    $row[] = $tposn;
    if ($range['type'] == 'genre') {
      $row[] = $obj->genre;
      $row[] = $obj->counter;
    }
    else {
      $row[] = $obj->artist;
      $row[] = $obj->titles;
      $row[] = $obj->counter;
    }
    $rows[] = $row;
  }
  if ($rowunspec) {
    $rowunspec[] = $countunspec;
    $rows[] = $rowunspec;
  }
  return $rows;
}

/**
 * Return an array of month numbers and names
 */
function fhreqchart_month_list() {
  static $arr = FALSE;
  if (!$arr) {
    $arr = array(
      1 => t('January'),
      2 => t('February'),
      3 => t('March'),
      4 => t('April'),
      5 => t('May'),
      6 => t('June'),
      7 => t('July'),
      8 => t('August'),
      9 => t('September'),
      10 => t('October'),
      11 => t('November'),
      12 => t('December'),
    );
  }
  return $arr;
}

/**
 * Return an array of year values
 *
 * @param $addthis
 *  If true, the current year is added, if its not already in the list.
 *  (Though if the list is empty, its added anyway.)
 */
function fhreqchart_year_list($addthis = FALSE) {
  static $years = FALSE;
  $y = date('Y');
  if (!$years) {
    $res = db_query("SELECT MIN(reqdate) as d1, MAX(reqdate) AS d2 FROM {fhreqchart}");
    if ($obj = db_fetch_object($res)) {
      $year1 = date('Y', $obj->d1);
      $year2 = date('Y', $obj->d2);
      $years = drupal_map_assoc(range($year1, $year2));
    }
    else {
      $years[$y] = $y;
    }
  }
  $rv = $years;
  if ($addthis and !in_array($y, $years)) {
    $rv[$y] = $y;
  }
  return $rv;
}

/**
 * Store data for a request.
 */
function fhreqchart_store_request(&$data) {
  $fields[] = 'artistid = '. fhreqchart_add_name('artist', $data['artist']);
  $fields[] = 'titleid = '. fhreqchart_add_name('title', $data['title']);
  $fields[] = 'wardid = '. fhreqchart_add_name('ward', $data['ward']);
  $fields[] = 'genreid = '. fhreqchart_add_name('genre', $data['genre']);
  $fields[] = 'reqdate = '. mktime(0, 0, 0, $data['month'], 1, $data['year']);
    
  if (!isset($data['reqid'])) {
    _fhreqchart_insert_request($fields);
  }
  else {
    db_query("UPDATE {fhreqchart} SET ". implode(", ", $fields) ." WHERE reqid = ". $data['reqid']);
    if (!db_affected_rows()) {
       _fhreqchart_insert_request($fields);
    }
  }
}

/*
 * Insert a new request
 */
function _fhreqchart_insert_request(&$fields) {
  db_query("INSERT INTO {fhreqchart} SET ". implode(", ", $fields));
}

/**
 * Add a name to a table and return its id. If the name already exists, just return the id.
 *
 * @param $which
 *   Which name to add: artist|title|ward
 * @param $name
 *   The name to add
 */
function fhreqchart_add_name($which, $name = FALSE) {
  if (empty($name) or $name == '?') {
    return 1; // unspecified value
  }
  $id = db_result(db_query("SELECT ". $which ."id FROM {fhreqchart_". $which ."} WHERE ". $which ." = '%s'", $name));
  if (!$id) {
    db_query("INSERT INTO {fhreqchart_". $which ."} (". $which .") VALUES('%s')", $name);
    $id = db_last_insert_id('fhreqchart_'. $which, $which .'id');
  }
  return $id;
}

/**
 * Return an array of the default search options
 */
function fhreqchart_search_range() {
  if (isset($_SESSION['fhreqchart'])) {
    $range = unserialize($_SESSION['fhreqchart']);
  }
  else {
    $d = getdate();
    $month = $d['mon'] - 1;   // last months chart
    $year = $d['year'];
    if ($month < 1) {
      $month = 12;
      $year--;
    }
    $range = array(
      'month' => $month,
      'year' => $year,
      'm2' => 0,
      'y2' => 0,
    );
  }
  $_SESSION['fhreqchart'] = serialize($range);
  return $range;
}

/**
 * @return string
 *  The where clause for the range.
 */
function _fhreqchart_range_where($range) {

  if (!$range['m2']) {
    // simple range, month & year
    $first = mktime(0, 0, 0, $range['month'], 1, $range['year'] );
    $where = " WHERE reqdate = $first ";
  }
  else {
    $d1 = mktime(0, 0, 0, $range['month'], 1, $range['year']);
    $d2 = mktime(0, 0, 0, $range['m2'], 1, $range['y2']);
    $first = min($d1, $d2);
    $last = max($d1, $d2);
    $where = " WHERE reqdate >= $first AND reqdate <= $last ";
  }
  return $where;
}

/**
 * Search the database
 *
 * @param $range
 *  The range of values to search for plus search type
 *
 * @return db resource
 */
function fhreqchart_query(&$range) {
  switch ($range['type']) {
    case 'track':
      $track = "CONCAT(CAST(r.artistid AS CHAR), CAST(r.titleid AS CHAR))";
      $query =
        "SELECT COUNT($track) as counter, art.artist, ttl.title as titles, ".
        "$track as track, r.artistid, r.titleid ".
        _fhreqchart_get_join(array('artist', 'title')) .
        _fhreqchart_range_where($range) .
        "GROUP BY track ORDER BY counter DESC, artist, title";
      break;
    case 'genre':
      $query =
        "SELECT COUNT(genre) as counter, gnr.genre, r.genreid ".
        _fhreqchart_get_join(array('genre')) .
        _fhreqchart_range_where($range) .
        "GROUP BY genre ORDER BY counter DESC, genre ";
      break;
    case 'artist':
    default:
      $query =
        "SELECT COUNT(artist) as counter, art.artist, ttl.title, art.artistid, ".
        "GROUP_CONCAT(DISTINCT ttl.title ORDER BY ttl.title SEPARATOR ', ') as titles ".
        _fhreqchart_get_join(array('artist', 'title')) .
        _fhreqchart_range_where($range) .
        "GROUP BY artist ORDER BY counter DESC, artist";
      break;
  }
  return db_query($query);
}

/**
 * Count the number of results for a range
 *
 * @param $range
 *   Array of values - the range to search for
 * @return
 *  Integer - the number of results for the range.
 */
function fhreqchart_count_range($range) {
  return db_result(db_query("SELECT COUNT(reqid) FROM {fhreqchart} ". _fhreqchart_range_where($range)));
}

/*
 * Add the JOIN part for the sql queries.
 */
function _fhreqchart_get_join($tables = array()) {
  $alias = array('artist' => 'art', 'title' => 'ttl', 'ward' => 'wrd', 'genre' => 'gnr');
  $join[] = "FROM {fhreqchart} r ";
  if (count($tables) == 0) {
    $tables = array('artist', 'title', 'ward', 'genre');
  }
  foreach ($tables as $tbl) {
    $join[] = sprintf('LEFT JOIN {fhreqchart_%1$s} %2$s ON r.%1$sid = %2$s.%1$sid ', $tbl, $alias[$tbl]);
  }
  return implode("\n", $join);
}

/**
 * Add the module css file, if required.
 */
function fhreqchart_add_css() {
  if (variable_get('fhreqchart_css', TRUE)) {
    drupal_add_css(drupal_get_path('module', 'fhreqchart') .'/fhreqchart.css');
  }
}

/**
 * Return the editing form for a request
 *
 * @param $reqid
 *  The id of the request to edit.
 */
function fhreqchart_edit_request($reqid) {
  $query =
    "SELECT r.reqid, art.artist, ttl.title, gnr.genre, wrd.ward, reqdate ".
    _fhreqchart_get_join() .
    "WHERE reqid = %d";
  $data = db_fetch_array(db_query($query, $reqid));
  $data['month'] = date('n', $data['reqdate']);
  $data['year'] = date('Y', $data['reqdate']);
  return drupal_get_form('fhreqchart_form_edit_request', $data);
}

/**
 * FAPI definition for the form for editing a request
 *
 * @ingroup forms
 */
function fhreqchart_form_edit_request(&$form_state, $data =  FALSE) {
  $months = fhreqchart_month_list();
  $years = fhreqchart_year_list(TRUE);
  $msg = variable_get('fhreqchart_record_msg', '');

  if (!$data) {
    $date = fhreqchart_get_record_date_range();
    $data = array(
      'month' => $date['month'],
      'year' => $date['year'],
      'artist' => '',
      'title' => '',
      'genre' => '',
      'ward' => '',
    );
  }

  // Initial focus on the artist field.
  drupal_add_js('$(document).ready(function () { $("#edit-artist").focus(); });', 'inline');

  $form['recform']['#theme'] = 'fhreqchart_edit_form';
  if ($msg != '') {
    $form['recform']['#prefix'] = '<div class="fhreqchart-left">';
    $form['recform']['#suffix'] = '<div class="fhreqchart-clear"></div></div>';
  }
  $form['recform']['month'] = array(
    '#type' => 'select',
    '#title' => t('Month'),
    '#options' => $months,
    '#default_value' => $data['month'],
  );

  $form['recform']['year'] = array(
    '#type' => 'select',
    '#title' => t('Year'),
    '#options' => $years,
    '#default_value' => $data['year'],
  );

  $form['recform']['artist'] = array(
    '#type' => 'textfield',
    '#title' => t('Artist'),
    '#size' => 30,
    '#default_value' => $data['artist'],
  );
  if (variable_get('fhreqchart_autocomplete', 1)) {
    $form['recform']['artist']['#autocomplete_path'] = 'fhreqchart/artistac';
  };

  $form['recform']['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#size' => 30,
    '#default_value' => $data['title'],
  );
  if (variable_get('fhreqchart_autocomplete', 1)) {
    $form['recform']['title']['#autocomplete_path'] = 'fhreqchart/titleac';
  };

  $form['recform']['ward'] = array(
    '#type' => 'textfield',
    '#title' => t('Ward'),
    '#size' => 30,
    '#default_value' => $data['ward'],
  );
  if (variable_get('fhreqchart_autocomplete', 1)) {
    $form['recform']['ward']['#autocomplete_path'] = 'fhreqchart/wardac';
  };

  $form['recform']['genre'] = array(
    '#type' => 'textfield',
    '#title' => t('Genre'),
    '#size' => 30,
    '#default_value' => $data['genre'],
  );
  if (variable_get('fhreqchart_autocomplete', 1)) {
    $form['recform']['genre']['#autocomplete_path'] = 'fhreqchart/genreac';
  };

  $form['recform']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  
  if ($msg != '') {
    $form['recmsg'] = array(
      '#type' => 'fieldset',
      '#theme' => 'fhreqchart_edit_msg',
      '#prefix' => '<div class="fhreqchart-msg">',
      '#suffix' => '<div class="fhreqchart-clear"></div></div>',
      );

    $form['recmsg']['msg'] = array(
      '#value' => '<div>'. $msg .'</div>',
      );
  }

  $form['reqid'] = array(
    '#type' => 'value',
    '#value' => $data['reqid'],
  );

  return $form;
}

/**
 * Format the request editing form
 *
 * @ingroup themeable
 */
function theme_fhreqchart_edit_form(&$form) {
  fhreqchart_add_css();
  $output[] = '<div>';
  $output[] =   '<div class="fhreqchart-left">'. drupal_render($form['month']) .'</div>';
  $output[] =   '<div class="fhreqchart-left2">'. drupal_render($form['year']) .'</div>';
  $output[] =   '<div class="fhreqchart-clear"></div>';
  $output[] = '</div>';
  $output[] = drupal_render($form);
  return implode("\n", $output);
}

/**
 * Format the edit message form.
 *
 * Done this way to allow later themeing.
 * @ingroup themeable
 */
function theme_fhreqchart_edit_msg($form) {
  $output[] = drupal_render($form);
  return implode("\n", $output);
}

/**
 * Submit the request editing form
 */
function fhreqchart_form_edit_request_submit(&$form, &$form_state) {
  $data['artist'] = ($form_state['values']['artist'] == '') ? t('Any') : $form_state['values']['artist'];
  $data['title'] = ($form_state['values']['title'] == '') ? t('Any') : $form_state['values']['title'];
  $data['genre'] = $form_state['values']['genre'];
  $data['ward'] = $form_state['values']['ward'];
  $data['reqid'] = $form_state['values']['reqid'];
  $data['month'] = $form_state['values']['month'];
  $data['year'] = $form_state['values']['year'];
  fhreqchart_store_request($data);
  fhreqchart_set_record_date_range( array('month' => $data['month'], 'year' => $data['year']) );
  drupal_set_message(t('Request saved'));
}

/**
 * Menu callback; Retrieve a JSON object containing autocomplete suggestions for existing artists.
 */
function fhreqchart_artist_autocomplete($string = '') {
  $matches = array();
  if ($string) {
    $result = db_query_range("SELECT artist FROM {fhreqchart_artist} WHERE LOWER(artist) LIKE LOWER('%s%%')",
                             $string, 0, 10);
    while ($obj = db_fetch_object($result)) {
      $matches[$obj->artist] = check_plain($obj->artist);
    }
  }
  drupal_json($matches);
}

/**
 * Menu callback; Retrieve a JSON object containing autocomplete suggestions for existing titles.
 */
function fhreqchart_title_autocomplete($string = '') {
  $matches = array();
  if ($string) {
    $result = db_query_range("SELECT title FROM {fhreqchart_title} WHERE LOWER(title) LIKE LOWER('%s%%')",
                            $string, 0, 10);
    while ($obj = db_fetch_object($result)) {
      $matches[$obj->title] = check_plain($obj->title);
    }
  }
  drupal_json($matches);
}

/**
 * Menu callback; Retrieve a JSON object containing autocomplete suggestions for existing wards.
 */
function fhreqchart_ward_autocomplete($string = '') {
  $matches = array();
  if ($string) {
    $result = db_query_range("SELECT ward FROM {fhreqchart_ward} WHERE LOWER(ward) LIKE LOWER('%s%%')",
                            $string, 0, 10);
    while ($obj = db_fetch_object($result)) {
      $matches[$obj->ward] = check_plain($obj->ward);
    }
  }
  drupal_json($matches);
}

/**
 * Menu callback; Retrieve a JSON object containing autocomplete suggestions for existing genres.
 */
function fhreqchart_genre_autocomplete($string = '') {
  $matches = array();
  if ($string) {
    $result = db_query_range("SELECT genre FROM {fhreqchart_genre} WHERE LOWER(genre) LIKE LOWER('%s%%')",
                             $string, 0, 10);
    while ($obj = db_fetch_object($result)) {
      $matches[$obj->genre] = check_plain($obj->genre);
    }
  }
  drupal_json($matches);
}

function fhreqchart_set_record_date_range($range) {
  $_SESSION['fhreqchart_recrange'] = serialize($range);
}

function fhreqchart_get_record_date_range() {
  if (isset($_SESSION['fhreqchart_recrange'])) {
      return unserialize($_SESSION['fhreqchart_recrange']);
  }
  $range = array('month' => date('n'), 'year' => date('Y'));
  fhreqchart_set_record_date_range($range);
  return $range;
}

function fhreqchart_settings_form(&$form_state) {
  $form['fhreqchart_record_msg'] = array(
    '#type' => 'textarea',
    '#title' => t('Record chart message'),
    '#description' => t('A message to be displayed on the form to record requests.'),
    '#default_value' => variable_get('fhreqchart_record_msg', ''),
  );

  $form['fhreqchart_autocomplete'] = array(
    '#type' => 'select',
    '#title' => t('Autocomplete names'),
    '#default_value' => variable_get('fhreqchart_autocomplete', 1),
    '#options' => array(0 => t('No'), 1 => t('Yes')),
  );

  return system_settings_form($form);
}

/**
 * FAPI definition of the form to download the request list.
 */
function fhreqchart_download_form(&$form_state) {
  fhreqchart_add_css();
  /* Get the range and type of search */
  if (isset($_SESSION['fhreqchart'])) {
    $range = unserialize($_SESSION['fhreqchart']);
    unset($_SESSION['fhreqchart']);
  }
  else {
    // New search
    $d = getdate();
    $month = $d['mon'] - 1;   // last months chart
    $year = $d['year'];
    if ($month < 1) {
      $month = 12;
      $year--;
    }
    $range = array(
      'month' => $month,
      'year' => $year,
      'm2' => 0,
      'y2' => 0,
    );
    $range['type'] = 'artist';
  }

  $months = fhreqchart_month_list();
  $years = fhreqchart_year_list(FALSE);
  
  $form['req_range']['caption'] = array(
    '#value' => t('Select type and period for the report to be downloaded.'),
  );
  $form['req_range'] += _fhreqchart_range_form($range);
  
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#description' => t('Title to display at the top of the report.'),
    '#default_value' => variable_get('fhreqchart_report_title', ''),
  );

  $form['notes'] = array(
    '#type' => 'textarea',
    '#title' => t('Notes'),
    '#description' => t('Optional additional notes to appear at the top of the report'),
    '#default_value' => variable_get('fhreqchart_report_notes', ''),
  );

  $form['range'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show range'),
    '#description' => t('Display the range for the search on the report.'),
    '#default_value' => variable_get('fhreqchart_report_showrange', TRUE),
  );
  
  $form['rangelabel'] = array(
    '#type' => 'textfield',
    '#title' => t('Range label'),
    '#description' => t('Label to display to the left of the range, if displayed.'),
    '#default_value' => variable_get('fhreqchart_report_rangelabel', ''),
  );

  $form['total'] = array(
    '#type' => 'checkbox',
    '#title' => t('Show total'),
    '#description' => t('Display the count of requests on the report.'),
    '#default_value' => variable_get('fhreqchart_report_total', TRUE),
  );

  return $form;
}

function fhreqchart_download_form_submit(&$form, &$form_state) {
  $range['month'] = $form_state['values']['month'];
  $range['year'] = $form_state['values']['year'];
  if ($form_state['values']['month2'] == 0 or $form_state['values']['year2'] == 0) {
    $range['m2'] = 0;
    $range['y2'] = 0;
  }
  else {
    $range['m2'] = $form_state['values']['month2'];
    $range['y2'] = $form_state['values']['year2'];
  }
  $range['type'] = $form_state['values']['type'];
  $title = $form_state['values']['title'];
  $notes = $form_state['values']['notes'];
  $showrange = $form_state['values']['range'];
  $rangelabel = $form_state['values']['rangelabel'];
  $total = $form_state['values']['total'];
  variable_set('fhreqchart_report_title', $title);
  variable_set('fhreqchart_report_notes', $notes);
  variable_set('fhreqchart_report_showrange', $showrange);
  variable_set('fhreqchart_report_rangelabel', $rangelabel);
  variable_set('fhreqchart_report_total', $total);

  $file = _fhreqchart_temp_file();
  if (!$file) {
    drupal_set_message(t('Unable to create temporary file.'));
  }
  else {
    $h = fopen($file, 'w');
    $header = _fhreqchart_header_row($range);
    $rows = _fhreqchart_report_rows($range);
    if ($title) {
      fwrite($h, '<h1 style="text-align:center">'. $title .'</h1>');
    }
    if ($showrange) {
      fwrite($h, '<p style="text-align: center">'. $rangelabel . theme('fhreqchart_show_range', $range) .'</p>');
    }
    if ($total) {
      $count = fhreqchart_count_range($range);
      fwrite($h, '<p style="text-align: center">'. theme('fhreqchart_total', $count) .'</p>');
    }
    if ($notes) {
      fwrite($h, '<p>'. $notes .'</p>');
    }
    fwrite($h, theme('table', $header, $rows));
    fclose($h);
    file_transfer($file, array());
  }
}

/**
 * Return the name of a temporary file in the modules own temporary folder.
 *
 * @return
 *  The path, or FALSE on error
 */
function _fhreqchart_temp_file() {
  return file_directory_temp() .'/fhrequest_'. date('YmdHis');
}
